import axios from 'axios'
import { Log } from '~/utils'
import TranslateEngine, { TranslateOptions, TranslateResult } from './base'

const qwen = axios.create({
  baseURL: 'http://192.168.130.200:8103/v1',
  headers: {
    'Authorization': 'Bearer ak-test-123',
    'Content-Type': 'application/json'
  }
})

qwen.interceptors.request.use((req) => {
  Log.info(`[Qwen] Request:${req.method},${req.url}`)
  return req
})

qwen.interceptors.response.use((res) => {
  Log.info(`[Qwen] Response:${res.status},${JSON.stringify(res.data)}`)
  return res
})

class QwenTranslateEngine extends TranslateEngine {
  async translate(options: TranslateOptions): Promise<TranslateResult> {
    try {
      const res = await qwen.post('/chat/completions', {
        model: 'qwen3-30b',
        messages: [{
          role: 'user',
          content: `/no_think帮我翻译以下文字到${options.to}: ${options.text}`
        }],
        stream: false,
        enable_thinking: false,
        temperature: 0.1,
        translation_options: {
          source_lang: options.from || 'auto',
          target_lang: options.to
        }
      })

      const content = res.data.choices[0]?.message?.content.replace(/<\/?think>|\n/g, '')
      const result = this.parseContent(content, options.to as string)

      return {
        text: options.text,
        from: options.from || 'auto',
        to: options.to as string,
        response: res.data,
        linkToResult: '',
        result: [result],
        detailed: [content]
      }
    } catch (error) {
      Log.error(`[Qwen] Translation error: ${error}`)
      throw error
    }
  }

  private parseContent(content: string, lang: string): string {
    try {
      const jsonStart = content.indexOf('{')
      if (jsonStart === -1) return content
      
      const jsonStr = content.slice(jsonStart)
      const json = JSON.parse(jsonStr)
      return json[lang] || content
    } catch {
      return content
    }
  }
}

export default QwenTranslateEngine